package cn.cj.erp.common.security.security.service;

import cn.cj.erp.bo.system.SysUserBo;
import cn.cj.erp.common.constants.SystemConstants;
import cn.cj.erp.common.enums.StatusEnum;
import cn.cj.erp.common.exception.ServiceException;
import cn.cj.erp.common.security.security.user.LoginUser;
import cn.cj.erp.service.system.SysUserService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysPasswordService passwordService;
    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserBo user = sysUserService.getByUsername(username);
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (StatusEnum.ABNORMAL.equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        // 超期未修改密码
        long diffDays = DateUtil.between(user.getLastPassTime(), new Date(), DateUnit.DAY);
        if (diffDays > SystemConstants.MAX_DAY_UPDATE_PASSWORD) {
            log.info("账号已有{}天未修改，锁定账号【username={}】", SystemConstants.MAX_DAY_UPDATE_PASSWORD, username);
            if (sysUserService.updateStatusByUsername(username, StatusEnum.ABNORMAL)) {
                throw new ServiceException("锁定账号失败");
            }
            throw new ServiceException(String.format("账号已有%d天未修改，锁定账号", SystemConstants.MAX_DAY_UPDATE_PASSWORD));
        }
        passwordService.validate(user);

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUserBo user) {
        LoginUser loginUser = new LoginUser();
        BeanUtil.copyProperties(user, loginUser);
        loginUser.setPermissions(permissionService.getMenuPermission(user));
        loginUser.setUser(user);
        return loginUser;
    }
}
